<template>
  <div
    class="app-container"
    v-loading="uploadLoading"
    :element-loading-text="uploadTetx"
    element-loading-spinner="el-icon-loading"
  >
    <avue-crud
      :option="option"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      @on-load="onLoad"
      @current-change="currentChange"
      @search-change="searchChange"
      @search-reset="resetChange"
      :cell-class-name="addClass"
      @cell-click="handleDownExcel"
    >
      <template slot="menuLeft">
        <div style="display: flex">
          <el-button
            v-has="'subscribeExport'"
            type="primary"
            icon="el-icon-download"
            size="small"
            :loading="downLoading"
            @click.stop="handelDownloadTemp"
          >模板下载</el-button>
          <el-upload
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
            :on-error="onError"
            :headers="headers"
            :action="importCustomer"
            v-has="'blackImport'"
          >
            <el-button
              type="primary"
              size="small"
              :icon="importDataBtnIcon"
            >
              {{ importDataBtnText }}
            </el-button>
          </el-upload>
        </div>
      </template>
    </avue-crud>
  </div>
</template>

<script>
import {
  getTableDataList,
  expCtmp,
  exportExcel,
  jrfkWhitelistZbHis,
} from '@/api/manager.js'
import axios from 'axios'
import store from '@/store'
import { downloadTemp } from '@/api/user.js'
export default {
  data() {
    return {
      loading: false, //table表格loading
      downLoading: false, //模板下载按钮loding
      uploadLoading: false, //导入按钮loding
      uploadTetx: '文件上传中......', //导入按钮loding
      importCustomer: '', //导入路径
      importDataBtnText: '导 入',
      importDataBtnIcon: 'el-icon-upload2',
      searchList: {},
      uploadName: '',
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        background: false,
      },
      data: [],
      option: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        card: true,
        defaultExpandAll: true,
        dialogDrag: false,
        labelWidth: 135,
        viewBtn: false,
        delBtn: false,
        excelBtn: false,
        editBtn: false,
        addBtn: false,
        selection: false,
        searchLabelWidth: '25%',
        searchSpan: 6,
        searchMenuSpan: 4,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        searchShowBtn: false,
        menu: false,
        column: [
          {
            label: '文件名称',
            prop: 'filename',
            display: false,
            search: true,
          },
          {
            label: '上传时间',
            prop: 'createtime',
            display: false,
            search: true,
            searchRange: true,
            type: 'datetime',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            searchSpan: 9,
          },
          {
            label: '白名单匹配结果',
            prop: 'bk',
            display: false,
            search: false,
          },
        ],
      },
    }
  },
  created() {
    this.importCustomer =
      process.env.VUE_APP_BASE_API + '/customer/jrfkBmdsxQy/import'
  },
  computed: {
    headers() {
      return {
        TOKEN: this.$store.getters.token,
      }
    },
  },
  methods: {
    addClass({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 3) {
        return 'cellSelect'
      }
    },
    //手动点击下载
    handleDownExcel(row, column, cell, event) {
      if (column.label == '白名单匹配结果') {
        this.uploadLoading = true
        this.uploadTetx = '文件下载中....'
        let params = { id: row.id }
        jrfkWhitelistZbHis(params).then((res) => {
          this.uploadLoading = false
          let fileName = row.bk + '.xlsx'
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(new Blob([res]))
          link.download = fileName
          link.click()
          //释放内存
          window.URL.revokeObjectURL(link.href)
        })
      }
    },
    onLoad(page, params = {}) {
      let searchList = this.searchList
      console.log(searchList)
      Object.assign(params, {
        ...searchList,
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
      })
      this.loading = true
      getTableDataList(params).then((data) => {
        if (data.operate == 'success') {
          this.loading = false
          this.data = data.data.records
          this.page.total = data.data.total
        }
      })
    },
    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      console.log(params)
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      if (params.createtime) {
        params.startDate = params.createtime[0]
        params.endDate = params.createtime[1]
      }
      params.createtime = []
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    //模板下载
    handelDownloadTemp() {
      expCtmp().then((res) => {
        let fileName = '白名单匹配模板.xlsx'
        var link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([res]))
        link.download = fileName
        link.click()
        //释放内存
        window.URL.revokeObjectURL(link.href)
      })
    },
    //上传成功导出接口
    exportExcel(e) {
      let params = { id: e }
      exportExcel(params).then((res) => {
        this.onLoad()
        this.uploadLoading = false
        let fileName = this.uploadName + '-白名单匹配报告.xlsx'
        var link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([res]))
        link.download = fileName
        link.click()
        //释放内存
        window.URL.revokeObjectURL(link.href)
      })
    },
    //上传前校验
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, '')
      if (['xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请使用下载的模板，上传后缀名为xlsx的文件！',
        })
        return false
      }
      this.importDataBtnText = '正在导入'
      this.importDataBtnIcon = 'el-icon-loading'
      this.uploadLoading = true
    },
    //上传成功
    onSuccess(response, file, fileList) {
      let fileIndex = file.name.lastIndexOf('.')
      this.uploadName = file.name.substring(0, fileIndex)
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      //this.onLoad(this.page);
      // this.$message({
      //     type: "success",
      //     message: "导入成功!"
      // });
      if (response.status) {
        this.exportExcel(response.data)
        this.uploadTetx = '文件下载中....'
      }
    },
    //上传失败
    onError(err, file, fileList) {
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      this.onLoad(this.page)
      this.uploadLoading = false
      this.$message({
        type: 'error',
        message: '导入失败!',
      })
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .cellSelect {
  color: #409eff !important;
  cursor: pointer;
}
/deep/ .avue-crud__pagination {
  text-align: center;
}
.dialog-footer {
  text-align: center;
  margin: 20px auto;
}
.tips {
  color: #4a8bf6;
  font-size: 14px;
}
.detailtable {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  border: #e5e5e5 solid 1px;
}
.detailtable tr {
  width: 100%;
}
.detailtable td {
  padding: 8px 10px;
  text-align: left;
  line-height: 24px;
  font-size: 14px;
  color: #434343;
  border: #e5e5e5 solid 1px;
}
.detailtable td {
  font-weight: normal;
  background-color: #fff;
}
.detailtable td {
  word-break: break-all;
}
</style>
